import rec from './rec.coffee'

import Crop from '~/worker/crop?worker'
import platform from '@/config/platform.mjs'
import config from '~/store/record.coffee'
import {audio as media_get_audio} from '~/lib/media_get.coffee'
import video_desktop from '~/lib/video_desktop.coffee'
import ipc from '~/lib/ipc.coffee'
import {watch} from 'vue'

{camera} = ipc

s = await video_desktop()

track = s.getVideoTracks()[0]

{area} = config
if area
  #await track.applyConstraints frameRate: { ideal: 15, max: 15 }

  tr = new MediaStreamTrackProcessor({ track , maxBufferSize:15})
  track = new MediaStreamTrackGenerator({ kind: 'video' })

  msg = [
    tr.readable
    track.writable
  ]

  on_rec = =>
    (new Crop()).postMessage(
      [
        localStorage.ppi - 0
        ...msg
        ...JSON.parse(localStorage.area)
      ]
      msg # 移交所有权
    )
    return

track.contentHint = 'detail'

audioSrc = await media_get_audio()

audio_li = if audioSrc then audioSrc.getTracks() else []

stream = new MediaStream [
  track
  ...audio_li

]

watchEffect =>
  audio = !!config.audio
  for i from audio_li
    i.enabled = audio
  return

watch(
  =>
    config.video
  =>
    {video} = config
    if video
      await camera.circle(localStorage.人像尺寸 - 0)
    else
      await camera.x()
    return
)

rec stream,on_rec
